<template>
  <div class="animated fadeIn">
    <div class="card card-accent-primary">
        <b-row>
          <b-col cols="12">
            <Card style="margin-bottom: 10px">
              <Form inline>
                <FormItem style="margin-bottom: 0">
                  <Select placeholder="请选择用户分组" clearable @on-change="checkGroup">
                    <Option v-for="item in authGroup" :value="item.ag_id" :key="item.ag_id">{{item.ag_title}}</Option>
                  </Select>
                </FormItem>
                <FormItem style="margin-bottom: 0">
                  <DatePicker type="daterange" @on-change="checkTime" placement="bottom" placeholder="选择创建时间段"></DatePicker>
                </FormItem>
                <FormItem style="margin-bottom: 0">
                  <Input v-model="key" placeholder="请输入用户名" style="width:150px;"></Input>
                </FormItem>
                <FormItem style="margin-bottom: 0">
                  <Button type="primary" @click="search">查询</Button>
                </FormItem>
              </Form>
            </Card>
          </b-col>
        </b-row>
        <b-row>
          <b-col cols="12">
            <Card>
              <p slot="title" style="height: 32px; margin-bottom: 0">
                <Button type="primary" @click="add" icon="plus-round">新增</Button>
              </p>
              <div>
                <i-table :loading="loading" border :columns="columns" :data="items"></i-table>
              </div>
              <div style="margin: 10px;overflow: hidden">
                <Page :total="total" :page-size="10" @on-change="onChange" show-total></Page>
              </div>
            </Card>
          </b-col>
        </b-row>
    </div>
    <Modal v-model="modalSetting.show" width="668" :styles="{top: '100px'}"  @on-visible-change="doCancel">
      <div slot="header" style="color:#2d8cf0;">
        <Icon type="information-circled"></Icon>
        <b>{{dataId ? '编辑' : '新增'}}用户</b>
      </div>
      <Form ref="formValidate" label-position="left" :label-width="80" :model="formItems" :rules="ruleValidate">
          <formItem label="用户名:" prop="name">
            <Input type="text" v-model="formItems.name"></Input>
          </formItem>
          <formItem label="密码:" prop="pwd">
            <Input type="password" v-model="formItems.pwd"></Input>
          </formItem>
        <formItem label="用户组:">
          <Select  v-model="formItems.ag_id" style="width:200px">
            <Option v-for="item in authGroup" :value="item.ag_id" :key="item.ag_id">{{item.ag_title}}</Option>
          </Select>
        </formItem>
          <formItem label="用户头像:">
            <div class="demo-upload-list"  v-for="(item, index) in uploadList" :key="index">
              <template v-if="item.status === 'finished'">
                <img :src="item.url">
                <div class="demo-upload-list-cover">
                  <Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
                  <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                </div>
              </template>
              <template v-else>
                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
              </template>
            </div>
            <Upload
              v-show="uploadList.length < 1"
              ref="upload"
              :default-file-list="defaultList"
              :headers="headers"
              :show-upload-list="false"
              :on-success="handleSuccess"
              :format="['jpg','jpeg','png']"
              :max-size="2048"
              :on-format-error="handleFormatError"
              :on-exceeded-size="handleMaxSize"
              type="drag"
              action="/api/common/fileupliad/"
              style="display: inline-block;width:58px;">
              <div style="width: 58px;height:58px;line-height: 58px;">
                <Icon type="camera" size="20"></Icon>
              </div>
            </Upload>
            <Modal title="图片预览" v-model="visible">
              <img :src="formItems.headpic" v-if="visible" style="width: 100%">
            </Modal>
          </formItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancel" style="margin-right: 8px">取消</Button>
        <Button type="primary" @click="submit('formValidate')" :loading="modalSetting.loading">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import Mixin from 'common/js/mixin'
import moment from 'moment'
import {Base64} from 'js-base64'
export default {
  data () {
    return {
      modalSetting: {
        show: false,
        loading: false
      },
      dataId: 0,
      formItems: {
        name: '',
        pwd: '',
        headpic: '',
        ag_id: 1
      },
      ruleValidate: {
        name: [
          {required: true, message: '请填写用户名', trigger: 'blur'}
        ],
        pwd: [
          {required: true, message: '请填写密码', trigger: 'blur'}
        ]
      },
      visible: false,
      uploadList: [],
      defaultList: [
        {
          'url': ''
        }
      ],
      headers: {
        'authkey': JSON.parse(localStorage.getItem('user_info')).auth_key
      },
      key: '',
      columns: [
        {
          title: 'ID',
          key: 'user_id',
          width: 50
        },
        {
          title: '用户名',
          key: 'user_name',
          width: 200
        },
        {
          title: '头像',
          key: 'user_headpic',
          render: (h, params) => {
            return h('Avatar', {
              props: {
                src: params.row.user_headpic
              }
            })
          },
          width: 200
        },
        {
          title: '状态',
          key: 'user_is_open',
          width: 100,
          render: (h, params) => {
            return h('i-switch', {
              props: {
                value: this.userSwitch(params.row.user_is_open)
              },
              scopedSlots: {
                open: () => h('span', '开'),
                close: () => h('span', '关')
              },
              on: {
                input: () => {
                  this.userChange(params.row.user_id, params.row.user_is_open)
                }
              }
            })
          }
        },
        {
          title: '用户分组',
          key: 'ag_title',
          width: 200,
          render: (h, params) => {
            return h('span', {
              'class': 'badge badge-success'
            }, params.row.ag_title)
          }
        },
        {
          title: '创建日期',
          key: 'user_createtime',
          width: 200,
          render: (h, params) => {
            return h('div', this.time(params.row.user_createtime))
          }
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          className: 'table-min-width',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.editItem(params.row.user_id)
                  }
                }
              }, '修改'),
              h('Button', {
                props: {
                  type: 'error'
                },
                on: {
                  click: () => {
                    this.deleteItem(params.row.user_id)
                  }
                }
              }, '删除')
            ])
          }
        }
      ],
      items: [],
      total: 0,
      page: 1,
      loading: true,
      authGroup: [],
      where: {}
    }
  },
  methods: {
    submit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          // 添加
          if (this.id === 0) {
            this.$post('/api/admin/user', this.formItems).then((res) => {
              if (res) {
                this.$Message.success({
                  content: res.mess,
                  onClose: () => {
                    this.cancel()
                    this.getList()
                  }
                })
              }
            })
          } else { // 修改
            this.$put('/api/admin/user/', this.dataId, this.formItems).then((res) => {
              if (res) {
                this.$Message.success({
                  content: res.mess,
                  onClose: () => {
                    this.cancel()
                    this.getList()
                  }
                })
              }
            })
          }
        }
      })
    },
    onChange (page) {
      this.page = page
      this.getList()
    },
    // 获取修改内容
    editItem (id) {
      this.$get('/api/admin/user/' + id).then((res) => {
        if (res) {
          this.modalSetting.show = true
          this.dataId = id
          this.formItems.name = res.data.user_name
          this.formItems.pwd = res.data.user_pwd
          this.formItems.headpic = res.data.user_headpic
          this.formItems.ag_id = res.data.ag_id
          this.defaultList[0].url = res.data.user_headpic
        }
      })
    },
    // 获取列表
    getList (key) {
      this.$get('/api/admin/user', {
        params: {
          page: this.page,
          key: key
        }
      }).then((res) => {
        if (res) {
          this.total = res.data.total
          this.items = res.data.data
          this.loading = false
        }
      })
    },
    // 用户状态
    userSwitch (val) {
      return val === 1
    },
    // 删除
    deleteItem (id) {
      this.$Modal.confirm({
        title: '提醒',
        content: '确认要删除吗?',
        onOk: () => {
          this.$_delete('/api/admin/user/', id).then((res) => {
            if (res) {
              this.$Message.success({
                content: res.mess,
                onClose: () => {
                  this.getList()
                }
              })
            }
          })
        }
      })
    },
    // 添加
    add () {
      this.uploadList = []
      this.modalSetting.show = true
    },
    // 用户改变状态
    userChange (id, status) {
      let userStatus = !status === true ? 1 : 0
      this.$post('/api/admin/user/changeStatus', {id: id, status: userStatus}).then((res) => {
        this.getList()
      })
    },
    // 搜索按钮
    search () {
      this.getList(this.key)
    },
    time (value) {
      let day = moment.unix(value)
      let date = moment(day).format('YYYY/MM/DD H:mm')
      return date
    },
    checkGroup (value) {
      if (value) {
        this.where.agm_group_id = value
      } else {
        delete this.where.agm_group_id
      }
      this.getSearch()
    },
    getAuthGroup () {
      this.$get('/api/admin/authGroup', {page: 'nopage'}).then((res) => {
        if (res) {
          this.authGroup = res.data.data
        }
      })
    },
    checkTime (value) {
      if (value[0] !== '' && value[1] !== '') {
        value[0] = new Date(Date.parse(value[0].replace(/-/g, '/'))).getTime() / 1000
        value[1] = new Date(Date.parse(value[1].replace(/-/g, '/'))).getTime() / 1000
        this.where.user_createtime = ['between', value]
      } else {
        delete this.where.user_createtime
      }
      this.getSearch()
    },
    getSearch () {
      let params
      if (Object.keys(this.where).length === 0) {
        params = {page: this.page}
      } else {
        params = {page: this.page, where: Base64.encode(JSON.stringify(this.where))}
      }
      this.$get('/api/admin/user', {params}).then((res) => {
        this.total = res.data.total
        this.items = res.data.data
        this.loading = false
      })
    },
    handleView (name) {
      this.visible = true
    },
    handleRemove (file) {
      const fileList = this.$refs.upload.fileList
      this.$refs.upload.fileList.splice(fileList.indexOf(file), 1)
    },
    handleSuccess (res, file) {
      if (res.state === 0) {
        file.url = res.data.imgurl
        this.formItems.headpic = res.data.imgurl
      } else {
        this.$Message.error({
          content: res.mess
        })
      }
    },
    handleFormatError (file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
      })
    },
    handleMaxSize (file) {
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
      })
    },
    doCancel (data) {
      if (!data) {
        this.gataId = 0
        this.$refs['formValidate'].resetFields()
        this.modalSetting.loading = false
        this.uploadList = this.$refs.upload.fileList
      }
    },
    cancel () {
      this.modalSetting.show = false
    }
  },
  mounted () {
    this.uploadList = this.$refs.upload.fileList
  },
  created () {
    this.getAuthGroup()
    this.getList()
  },
  mixins: [Mixin]
}
</script>
<style>
    /*解决table表格适应问题*/
    .table-min-width {
      min-width: 200px;
      width: 200px;
    }
   .demo-upload-list{
     display: inline-block;
     width: 60px;
     height: 60px;
     text-align: center;
     line-height: 60px;
     border: 1px solid transparent;
     border-radius: 4px;
     overflow: hidden;
     background: #fff;
     position: relative;
     box-shadow: 0 1px 1px rgba(0,0,0,.2);
     margin-right: 4px;
   }
  .demo-upload-list img{
    width: 100%;
    height: 100%;
  }
  .demo-upload-list-cover{
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0,0,0,.6);
  }
  .demo-upload-list:hover .demo-upload-list-cover{
    display: block;
  }
  .demo-upload-list-cover i{
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
</style>
